<?php

class UrlClassController extends Controller
{
	
	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','ajaxgetlist','search','multipleupdate'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		echo 'greate';
		exit;
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new UrlClass;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		
		if(isset($_POST['UrlClass']))
		{
			$model->attributes=$_POST['UrlClass'];
			if($model->save()){
				$model->updateClassPath();
				showmsg('添加成功！',Yii::app()->createUrl('UrlClass/index'));
			}
		}
		//获取根分类
		$root_class = $model->getSubClass();
		$jsFile = Yii::app()->theme->baseUrl.'/assets/js/common.js';
		Yii::app()->clientScript->registerScriptFile($jsFile);
		$this->render('create',array(
			'model'=>$model,
			'root_class'=>$root_class,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate()
	{
		if(isset($_GET['id'])){
			$id = intval($_GET['id']);
		}
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['UrlClass']))
		{
			$model->attributes=$_POST['UrlClass'];
			if($model->save()){
				$model->updateClassPath();
				showmsg('更新成功！',Yii::app()->createUrl('UrlClass/index'));
				//$this->redirect(array('view','id'=>$model->classid));
			}
		}
		
		//获取根分类
		$root_class = $model->getSubClass();
		$class_path = explode('/', $model->path);
		array_pop($class_path);
		$class_path_ids =implode(',', $class_path);
		$class_path_names_string = $model->getClassNames($class_path);
		$this->render('update',array(
			'model'=>$model,
			'root_class'=>$root_class,
			'class_path'=>$class_path_ids,
			'class_path_names_string' =>$class_path_names_string,
		));
	}
	
	public function actionMultipleUpdate()
	{
		if(Yii::app()->request->isPostRequest)
		{
			$action = $_POST['action'];
			if($action == 'del'){
				$rmids = $_POST['rmid'];
				foreach ($rmids as $classid=>$value)
				{
					$this->loadModel($id)->delete();
				}
				showmsg('操作成功！', isset($_POST['returnUrl']) ? $_POST['returnUrl'] : yii::app()->createUrl('UrlClass/index'));
			}
			
		}else {
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}
		
		
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$criteria=new CDbCriteria(array(
			'condition'=>'parentid=0',
			'order'=>'displayorder DESC',
		));
		$dataProvider=new CActiveDataProvider('UrlClass',
													array(
														'criteria'=>$criteria,
													)
											 );
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}
	
	
	/**
	 * 异步请求分类列表
	 */
	public function actionAjaxGetList()
	{
		if(isset($_GET['parentid'])){ //GET 参数
			$parentid = intval($_GET['parentid']);
		} else {
			$parentid = 0;
		}
		$class_list = UrlClass::model()->getSubClass($parentid);
		if($class_list){
			echo CJSON::encode($class_list);
		} else {
			echo 'false';
		}
	}
	/**
	 * 查询分类
	 */
	public function actionSearch()
	{
		try
        {
					    
            if( isset($_GET['k']) )
            {
                header("Content-type: text/html; charset=utf-8");
                echo json_encode(UrlClass::model()->search_class($_GET['k']));
            }
            exit;
        }
        catch( Exception $e )
        {
            
        }
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new UrlClass('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['UrlClass']))
			$model->attributes=$_GET['UrlClass'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=UrlClass::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='url-class-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
